import { ref, type Ref } from 'vue'
// import { addThing, getNewItemId, load } from '@jcstdio/jc-utils/id'
import { addThing, getNewItemId, load } from '@/id/manager'
import type { PopupRecords, loglevel, PopupUnit } from './types'

class PopupStore {
  static _THING_NAME_ = '__JC_POPUP_MANAGER__'
  private _popupContainer: Ref<PopupRecords> = ref<PopupRecords>(new Map())

  constructor() {
    addThing(PopupStore._THING_NAME_)
    load(PopupStore._THING_NAME_)
  }

  public get popupsRef(): Ref<PopupRecords> {
    return this._popupContainer
  }

  /**
   * 添加日志器型弹窗
   * @param level
   * @param title
   * @param text
   * @returns 新弹窗的 ID 字符串
   */
  public addLogger(level: loglevel, title: string, text: string): string {
    const id = getNewItemId(PopupStore._THING_NAME_) as string
    this._popupContainer.value.set(id, {
      class: 'logger',
      level: level,
      title: title,
      text: text
    })
    return id
  }

  /**
   * 添加对话框型弹窗
   * @param title 弹窗的标题
   * @param text 弹窗描述文本
   * @param options 选项，键表示选项内容，值表示点击该选项时执行的函数
   */
  public addDialogue(title: string, text: string, options: Record<string, Function>): string {
    const id = getNewItemId(PopupStore._THING_NAME_) as string
    this._popupContainer.value.set(id, {
      class: 'dialogue',
      title: title,
      text: text,
      options: options
    })
    return id
  }

  /**
   * 依据 ID 删除相应的弹窗
   * @param id
   * @returns
   */
  public removePopup(id: string): Promise<unknown> {
    const popup: PopupUnit | undefined = this._popupContainer.value.get(id)
    return new Promise((resolve, rejects) => {
      if (popup) {
        try {
          this._popupContainer.value.delete(id)
          resolve(true)
        } catch (e) {
          rejects(e)
        }
      }
      rejects(`Popup does not exists.`)
    })
  }
}

const popupStore = new PopupStore()

/**
 * 新建日志弹窗
 * - 这种窗口将会依据调用的日志等级，记录相应的日志事件
 * @param level 日志级别
 * @param title 窗口标题
 * @param text 窗体文本
 */
function createLogger(level: loglevel, title: string, text: string) {
  return new Promise((resolve, rejects) => {
    try {
      const id: string = popupStore.addLogger(level, title, text)
      resolve(id)
    } catch (e) {
      rejects(`${e}`)
    }
  })
}

/**
 * 新建对话弹窗
 * @param title 窗口标题
 * @param text 窗体文本
 * @param options 选项集，每个选项的键将作为按钮文本，值为点击相应按钮时的回调函数
 * @returns
 */
function createDialogue(title: string, text: string, options: Record<string, Function>) {
  return new Promise((resolve, rejects) => {
    try {
      const id: string = popupStore.addDialogue(title, text, options)
      resolve(id)
    } catch (e) {
      rejects(`${e}`)
    }
  })
}

/**
 * 依据弹窗的 ID 关闭指定的弹窗
 * @param id
 * @returns
 */
function closePopup(id: string) {
  return popupStore.removePopup(id)
}

/**弹窗数据引用 */
function getPopupsRef(): Ref<PopupRecords> {
  return popupStore.popupsRef
}

export { getPopupsRef, createLogger, createDialogue, closePopup }
